package com.ror.java.se.map.hashmap;

import java.util.*;

public class Demo03HashMapVotes {
    public static void main(String[] args) {
        /* 需求
            某个班级80名学生，现在需要组成秋游活动，班长提供了四个景点依次是（A、B、C、D），每个学生只
            能选择一个景点，请统计出最终哪个景点想去的人数最多。
        */
        //1模拟投票
        String[] scenes = {"A", "B", "C", "D"};
        ArrayList<String> voteds = new ArrayList<>();
        Random r = new Random();
        for (int i = 0; i < 100; i++) {
            voteds.add(scenes[r.nextInt(scenes.length)]);
        }

        //2统计的东西较多时，用计数器思想很麻烦，此时用map集合更好，键为统计项，值为计数
        HashMap<String, Integer> votedCntMap = new HashMap<>();
        for (String voted : voteds) {
            if (!votedCntMap.containsKey(voted)) {
                votedCntMap.put(voted, 1);
                continue;
            }
            int voteCnt = votedCntMap.get(voted);
            votedCntMap.put(voted, ++voteCnt);
        }

        //3求最大值（键值对遍历）
        int maxVoteCnt = 0;
        String maxVoted = null;
        Set<Map.Entry<String, Integer>> entries = votedCntMap.entrySet();
        for (Map.Entry<String, Integer> entry : entries) {
            if (entry.getValue() > maxVoteCnt) {
                maxVoteCnt = entry.getValue();
                maxVoted = entry.getKey();
            }
        }

        //4打印哪个景点想去的人数最多
        System.out.println(entries);
        System.out.println("景点" + maxVoted + "想去的人数最多，为" + maxVoteCnt);
    }

}
